package CPU.rv64_5stage
import chisel3._
import chisel3.util._

class MEM2WB extends Bundle{
  val rfwdata = UInt(64.W)
  val rfwaddr = UInt(5.W)
  val rfwen   = Bool()
  val pcinst  = new IF2ID
}

class MemAccess extends Module{
  val io = IO(new Bundle{
    val memin = Input(new EX2MEM)
    val dmem  = new RamIO
    val mem2wb = Output (new MEM2WB)
  })
  io.mem2wb.pcinst  := io.memin.pcinst
  io.mem2wb.rfwaddr := io.memin.rfwaddr
  io.mem2wb.rfwen   := io.memin.rfwen

  io.dmem.wen := io.memin.wen
  io.dmem.wmask := io.memin.wmask
  io.dmem.wdata := io.memin.wdata
  io.dmem.en    := io.memin.en
  io.dmem.addr  := io.memin.addr
  val addroffset = io.memin.addr(2,0)
  val offsetdata = io.dmem.rdata >> (addroffset<<3)
  val load_data = MuxCase(0.U,Array(
    (io.memin.opcode===LSUOpType.lb)  -> SignExt(offsetdata(7,0),64),
    (io.memin.opcode===LSUOpType.lbu) -> ZeroExt(offsetdata(7,0),64),
    (io.memin.opcode===LSUOpType.lh)  -> SignExt(offsetdata(15,0),64),
    (io.memin.opcode===LSUOpType.lhu) -> ZeroExt(offsetdata(15,0),64),
    (io.memin.opcode===LSUOpType.lw)  -> SignExt(offsetdata(31,0),64),
    (io.memin.opcode===LSUOpType.lwu) -> ZeroExt(offsetdata(31,0),64),
    (io.memin.opcode===LSUOpType.ld)  -> offsetdata,
  ))
  io.mem2wb.rfwdata := Mux(io.memin.islsu,load_data,io.memin.exout)
}
